import { GetFieldDecoratorOptions } from "antd/lib/form/Form";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import FormCreator, { InputType } from "src/business/components/buss-components/form-creator";
import { MainContent } from "src/business/components/style-components/main-content";
import { AppServiceUtility } from "src/projects/app/appService";
// import { isPermission } from "src/projects/app/permission";
import { ROUTE_PATH } from "src/projects/router";
import { edit_props_info } from "src/projects/app/util-tool";
import { notification, Button, message, Steps, Card, Result, Row } from "antd";
import { request } from "src/business/util_tool";
import { SocietyInfo } from "../recipient-apply/society-info";
const { Step } = Steps;
import { CharitableDonateInfo } from "../charitable-donate/charitable-donate-info";
import TextArea from "antd/lib/input/TextArea";
import { checkPhone } from '../../activity-manage/validate';
/**
 * 组件：冠名基金详情
 */
export interface ChangeCharitableTitleFundViewState extends ReactViewState {
    /** 数据id */
    id?: string;
    // 慈善会信息
    society_info?: any;
    // 募捐步骤
    apply_step: any;
    // 申请步骤
    step?: number;
    // 状态
    status?: string;
    // 捐赠详情
    donate_info: any;
    // 审批不通过原因
    sp_msg?: string;
    // 是否已发送
    is_send: boolean;
}

/**
 * 组件：冠名基金详情
 */
export default class ChangeCharitableTitleFundView extends ReactView<ChangeCharitableTitleFundViewControl, ChangeCharitableTitleFundViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            step: -2,
            status: '',
            id: '',
            society_info: [],
            apply_step: [],
            donate_info: [],
            sp_msg: '',
            is_send: false,
        };
    }
    /** 确定回调 */
    handleSubmit = (err: Error, values: any) => {
        // 基金捐赠标识
        values['donate_type'] = '基金';
        request(this, AppServiceUtility.charitable_service.update_charitable_title_fund!(values))
            .then((data: any) => {
                if (data === 'Success') {
                    const notificationKey = `nk${Date.now()}`;
                    notification.open({
                        message: '申请成功',
                        description: '冠名基金申请申请提交成功，请等待审核！',
                        key: notificationKey,
                        btn: <Button type="primary" size="small" onClick={() => this.closedAndToList(notificationKey)}>确定</Button>,
                        onClose: () => {
                            this.closedAndToList(notificationKey);
                        },
                    });
                    setTimeout(
                        () => {
                            this.returnBtn();
                        }
                        ,
                        3000
                    );
                } else {
                    message.error(`错误信息：${data}`);
                }
            })
            .catch(error => {
                message.error(error.message);
            });
    }
    closedAndToList(notificationKey: any) {
        notification.close(notificationKey);
        this.returnBtn();
    }
    /** 返回回调 */
    returnBtn() {
        this.props.history!.push(ROUTE_PATH.viewCharitableTitleFund);
    }
    componentDidMount() {
        let param = (this.props.match!.params.code && this.props.match!.params.code === 'view') ? { all: true, id: this.props.match!.params.key } : { id: this.props.match!.params.key };

        if (this.props.match!.params.key) {
            request(this, AppServiceUtility.charitable_service.get_charitable_title_fund_list_all!(param, 1, 1))
                .then((datas: any) => {
                    let step_no = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['step_no']) ? datas.result[0]['new_field'][0]['step_no'] : ((datas.result && datas.result[0] && datas.result[0]['step_no']) ? datas.result[0]['step_no'] : -1);
                    let status = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['status']) ? datas.result[0]['new_field'][0]['status'] : ((datas.result && datas.result[0] && datas.result[0]['status']) ? datas.result[0]['status'] : '未知');
                    let donate_info = (datas.result && datas.result[0]) ? datas.result[0] : [];
                    this.setState({
                        step: step_no,
                        status,
                        donate_info,
                    });
                });
        } else {
            // 啥都没有，默认个人申请
            this.setState({
                step: 0,
                status: '待审批',
            });
        }
        // 获取基金步骤
        request(this, AppServiceUtility.charitable_service.get_recipient_step!({ 'step_type': '基金' }, 1, 1))
            .then((data: any) => {
                if (data) {
                    this.setState({
                        apply_step: data,
                    });
                } else {
                    message.error(`错误信息：${data}`);
                }
            })
            .catch(error => {
                message.error(error.message);
            });
        // 获取慈善会信息
        request(this, AppServiceUtility.charitable_service.get_charitable_society_list!({}, 1, 1))
            .then((data: any) => {
                if (data.result && data.result[0]) {
                    this.setState({
                        society_info: data.result[0] || [],
                    });
                }
            })
            .catch(error => {
                message.error(error.message);
            });
    }
    setRejectReason(e: any) {
        this.setState({
            sp_msg: e.target.value,
        });
    }
    setParam(step_no: number, status: string, sp_status: string, notcie: string) {
        let { sp_msg, donate_info } = this.state;
        if (sp_status === '不通过' && sp_msg === '') {
            message.error('不通过请填写原因');
            return;
        }
        let param: any = {
            // 审批标识
            'is_sp': 1,
            // 审批状态
            'sp_status': sp_status,
            // 主数据状态
            'status': status,
            // 审批信息
            'sp_msg': sp_msg,
            // 步骤
            'step_no': step_no,
            // 主键ID
            'id': donate_info['id'],
        };
        this.changeStatus(param, notcie);
    }
    changeStatus(value: any, notice: string) {
        const is_send = this.state.is_send;
        const that = this;
        notice = notice || '操作成功！';
        // 正在发送请求
        if (is_send === true) {
            message.error('请勿操作过快！');
            return;
        }
        this.setState(
            {
                is_send: true,
            },
            () => {
                request(that, AppServiceUtility.charitable_service.update_charitable_title_fund!(value))
                    .then((data: any) => {
                        if (data === 'Success') {
                            that.setState({
                                is_send: false,
                            });
                            message.success(notice, 3, () => this.returnList());
                        } else {
                            message.error(data);
                        }
                    }).catch((error: Error) => {
                        message.error(error.message);
                    });
            }
        );
        return;
    }
    // 返回审核列表
    returnList() {
        if (this.props.match!.params.code && this.props.match!.params.code === 'view') {
            this.props.history!.push(ROUTE_PATH.viewCharitableTitleFund);
        } else {
            this.props.history!.push(ROUTE_PATH.charitableTitleFund);
        }
    }
    returnApplyForm() {
        let edit_props = {
            form_items_props: [
                {
                    title: '冠名基金',
                    need_card: true,
                    input_props: [
                        {
                            type: InputType.antd_input,
                            label: "基金名字",
                            decorator_id: "donate_name",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入基金名字" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入基金名字",
                                autocomplete: 'off',
                            }
                        },
                        {
                            type: InputType.input_number,
                            label: "基金金额",
                            decorator_id: "donate_money",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入捐款金额" }],
                                initialValue: 500000,
                            } as GetFieldDecoratorOptions,
                            option: {
                                min: 500000,
                                step: 1,
                                placeholder: "请输入捐款金额",
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "基金意向",
                            decorator_id: "donate_intention",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入基金意向" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入基金意向",
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "救助对象",
                            decorator_id: "donate_object",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入救助对象" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入救助对象",
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "联系方式",
                            decorator_id: "contacts",
                            field_decorator_option: {
                                rules: [{
                                    required: true,
                                    validator: (_: any, value: any, cb: any) => checkPhone(_, value, cb, '联系方式')
                                }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入联系方式",
                            }
                        },
                        {
                            type: InputType.rangePicker,
                            label: "基金开放时间",
                            decorator_id: "open_date",
                            field_decorator_option: {
                                rules: [{ required: true, message: "基金开放时间" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: ['开始时间', '结束时间'],
                            }
                        },
                        {
                            type: InputType.text_area,
                            label: "基金描述",
                            decorator_id: "remark",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入基金描述" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入基金描述",
                                autocomplete: 'off',
                            }
                        },
                    ]
                }
            ],
            other_btn_propps: [
                {
                    text: "返回",
                    cb: () => {
                        this.props.history!.push(this.props.back_url ? this.props.back_url : ROUTE_PATH.charitableDonate);
                    }
                },
            ],
            submit_btn_propps: {
                text: "提交申请",
                cb: this.handleSubmit
            },
            service_option: {
                service_object: AppServiceUtility.charitable_service,
                operation_option: {
                    save: {
                        func_name: "update_charitable_title_fund"
                    },
                    query: {
                        func_name: "get_charitable_donate_list_all",
                        arguments: [{ id: this.props.match!.params.key }, 1, 1]
                    }
                },
            },
            succ_func: () => { this.props.history!.push(this.props.back_url ? this.props.back_url : ROUTE_PATH.viewCharitableTitleFund); },
            id: this.props.match!.params.key,
            extra_html: <SocietyInfo data_info={this.state.society_info} />
        };
        let edit_props_list = Object.assign(edit_props, edit_props_info);
        // const { apply_step } = this.state;
        return (
            <FormCreator {...edit_props_list} />
        );
    }
    returnInfoSH() {
        const donate_info = this.state.donate_info;
        let isView = this.props.match!.params.code;
        return (
            <Card>
                <CharitableDonateInfo donate_info={donate_info} />
                {isView ? null : <Row>
                    <br />
                    <Row>不通过请填写原因</Row>
                    <br />
                    <TextArea rows={4} onChange={(e) => { this.setRejectReason(e); }} />
                    <Row type="flex" justify="center" className="ctrl-btns">
                        <Button onClick={() => this.setParam(1, '不通过', '不通过', '')}>不通过</Button>
                        <Button type="primary" onClick={() => this.setParam(1, '待审批', '通过', '')}>审批通过</Button>
                    </Row>
                </Row>}
            </Card>
        );
    }
    returnWaitDonate() {
        return (
            <Card>
                <Result
                    status="info"
                    title={`等待支付！`}
                />
            </Card>
        );
    }
    render() {
        let { step, status, donate_info, apply_step } = this.state;
        let stepStatus: any = {};
        if (status === '不通过') {
            stepStatus.status = 'error';
        }
        // step为-1代表完成了，取数组长度
        step = step === -1 ? apply_step.length - 1 : step;
        return (
            <MainContent>
                <Steps current={step} {...stepStatus} style={{ background: "white", padding: "25px" }}>
                    {apply_step.map((item: any, index: number) => {
                        return (
                            <Step key={index} title={item.step_name} />
                        );
                    })}
                </Steps>
                {(() => {
                    if (status === '不通过') {
                        return (
                            <Card>
                                <Result
                                    status="error"
                                    title="审批不通过"
                                    subTitle={'不通过原因：' + (donate_info['sp_msg'] || '暂无')}
                                />
                            </Card>
                        );
                    } else if (status === '通过') {
                        return (
                            <Card>
                                <Result
                                    status="success"
                                    title="完成"
                                    subTitle={`申请通过！`}
                                />
                            </Card>
                        );
                    } else {
                        if (step === 0) {
                            // 申请表
                            return this.returnApplyForm();
                        } else if (step === 1) {
                            // 资料审批
                            return this.returnInfoSH();
                        } else if (step === 2) {
                            // 等待充值
                            return this.returnWaitDonate();
                        }
                    }
                    return null;
                })()}
            </MainContent>
        );
    }
}

/**
 * 控件：冠名基金详情
 * @description 冠名基金详情
 * @author
 */
@addon('ChangeCharitableTitleFundView', '冠名基金详情', '冠名基金详情')
@reactControl(ChangeCharitableTitleFundView, true)
export class ChangeCharitableTitleFundViewControl extends ReactViewControl {
    /** 上一页url */
    public back_url?: string;
}